import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:web_socket_channel/web_socket_channel.dart';

import '../provider/AuthProvider.dart';
import 'api.dart';

class MessageSocketService {
  late WebSocketChannel _channel;
  final BuildContext context;

  MessageSocketService(this.context);

  void connect() {
    final authProvider = Provider.of<AuthProvider>(context, listen: false);
    final userId = authProvider.userId;

    if (userId == null) {
      print("未登录，无法建立 WebSocket");
      return;
    }

    _channel = WebSocketChannel.connect(
      Uri.parse('${Api.wsBaseUrl}/chat?userId=$userId'),
    );

    _channel.stream.listen(
      (data) {
        print("📥 收到服务器推送: $data");

        final msg = jsonDecode(data);

        if (msg['type'] == 'chat') {
          _handleIncomingMessage(msg);
        } else if (msg['type'] == 'system') {
          // 可扩展处理系统消息
        }
      },
      onDone: () {
        print("WebSocket连接断开");
      },
      onError: (error) {
        print("WebSocket错误: $error");
      },
    );
  }

  void _handleIncomingMessage(Map<String, dynamic> msg) {
    final fromUserId = msg['from'];
    final messageId = msg['messageId'];

    // TODO：添加到本地聊天记录状态管理中（PostProvider 或 MessageProvider）

    // ✅ 发送 ACK 回执
    final ack = {
      "type": "ack",
      "from": msg['to'], // 当前用户
      "to": fromUserId,
      "messageId": messageId,
    };
    _channel.sink.add(jsonEncode(ack));
    print("✅ 已发送 ACK 回执");
  }

  void sendMessage(String toUserId, String content) {
    final authProvider = Provider.of<AuthProvider>(context, listen: false);
    final fromUserId = authProvider.userId;
    if (fromUserId == null) return;

    final msg = {
      "type": "chat",
      "from": "$fromUserId",
      "to": toUserId,
      "content": content,
      "timestamp": DateTime.now().millisecondsSinceEpoch,
    };
    _channel.sink.add(jsonEncode(msg));
  }

  void disconnect() {
    _channel.sink.close();
  }
}
